<script setup lang="ts">
import {onMounted, reactive, h, ref} from "vue";
import {NTag, NButton, NDivider} from "naive-ui";
import {Search} from "@vicons/tabler"
import {clone} from "@renderer/utils/index"

const formRef = ref<HTMLFormElement | null>(null);
const searchForm = reactive({
  username: '',
  current: 1,
  size: 10
})
let operator = ref('Add')
const showModal = ref(false);
const modalTitle = ref("添加操作员")
//表单数据
let formData = ref({
  username: '',
  password: '',
  repassword: '',
  mobile: '',
  realname: '',
  status: '1'
})

const validateRepeatPassword = (rule, value) => {
  return value === formData.value.password
}

// 校验规则
const rules = reactive({
  username: {
    required: true,
    message: '请输入用户名',
    trigger: 'blur'
  },
  password: {
    required: true,
    message: '请输入密码',
    trigger: 'blur'
  },
  mobile: {
    required: true,
    message: '请输入手机号',
    trigger: 'blur'
  },
  repassword: [{
    required: true,
    message: '请输入密码',
    trigger: 'blur'
  },{
    validator: validateRepeatPassword,
    message: '两次密码输入不一致',
    trigger: 'blur'
  },],
  status: {
    required: true,
    message: '请选择状态',
    trigger: 'change'
  },
})
// 表格数据
let tableData = ref({
  page: [],
  total: 0
})

const columns = reactive([
  {
    title: '序号',
    key: 'id',
    width: '60px',
    align: 'center',
    render: (_, index) => {
      return `${index + 1}`
    }
  },
  {
    title: '用户名',
    key: 'username',
    width: '150px',
  },
  {
    title: '手机号',
    key: 'mobile',
    width: '150px',
  },
  {
    title: '真实姓名',
    key: 'realname',
    width: '150px',
  },
  {
    title: '状态',
    key: 'status',
    width: '80px',
    align: 'center',
    render: (row) => {
      if(row.status == 1) {
        return h(
            NTag,
            {
              type: 'success',
              size: 'small'
            },
            { default: () => '启用' }
        )
      }else{
        return h(
            NTag,
            {
              type: 'default',
              size: 'small'
            },
            { default: () => '禁用' }
        )
      }
    }
  },
  {
    title: '操作',
    key: 'status',
    render: (row) => {
      return [h(
          NButton,
          {
            type: 'warning',
            size: 'tiny',
            secondary: true,
            strong: true,
            onClick: () => handleToUpdateClick(row)
          },
          { default: () => '编辑' }
      ),
        h(NDivider,
            {
              vertical: true
            },
            null
        ),
        h(
            NButton,
            {
              type: 'error',
              size: 'tiny',
              secondary: true,
              strong: true,
              onClick: () => handleDeleteClick(row.id)
            },
            { default: () => '删除' }
        )]
    }
  }
])

// 搜索
const handleSearchClick = () => {
  loadData()
}
// 分页
const handlePageChange = (page) => {
  searchForm.current = page
  loadData()
}
// 添加弹窗
const handleToAddClick = () => {
  modalTitle.value = '添加操作员'
  operator.value = 'Add'
  formData.value = {
    username: '',
    password: '',
    mobile: '',
    realname: '',
    status: '1'
  }
  showModal.value = true
}
const handleToUpdateClick = (row) => {
  modalTitle.value = '编辑操作员'
  operator.value = 'Edit'
  formData.value = clone(row)
  formData.value.status += ''
  showModal.value = true
}
// 添加
const handleSaveClick = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      if(operator.value == 'Add'){
        window.electron.ipcRenderer.invoke("renderer-to-main", {
          name: 'app-operator-add',
          event: 'event',
          data: clone(formData.value)
        })
      } else {
        window.electron.ipcRenderer.invoke("renderer-to-main", {
          name: 'app-operator-update',
          event: 'event',
          data: clone(formData.value)
        })
      }
    }
  })
}

// 加载表格数据
const loadData = () => {
  window.electron.ipcRenderer.invoke("renderer-to-main", {
    name: 'app-operator-page',
    event: 'event',
    data: clone(searchForm)
  })
}
// 删除
const handleDeleteClick = (id) => {
  window.electron.ipcRenderer.invoke("renderer-to-main", {
    name: 'app-operator-delete',
    event: 'event',
    data: id
  })
}

onMounted(() => {
  window.electron.ipcRenderer.on('main-to-renderer', (e, data) => {
    const event = data.data
    if(data.name === 'operator-page-success'){
      tableData.value = event
    }else if(data.name === 'operator-operator-success'){
      window.$message.success(event);
      showModal.value = false
      loadData()
    }else if(data.name === 'operator-operator-error'){
      window.$message.error(event);
    }
  })
  loadData()
})
</script>

<template>
  <n-space vertical>
    <div class="dreamer-search">
      <n-form inline :label-width="80" :model="searchForm" size="small">
        <n-form-item  label="用户名" path="searchForm.username">
          <n-input v-model:value="searchForm.username" clearable placeholder="输入用户名" />
        </n-form-item>
        <n-form-item  label="手机号" path="searchForm.mobile">
          <n-input v-model:value="searchForm.mobile" clearable placeholder="输入手机号" />
        </n-form-item>
        <n-form-item>
          <n-button type="primary" attr-type="button" @click="handleSearchClick">
            <template #icon>
              <n-icon>
                <Search />
              </n-icon>
            </template>
            搜索
          </n-button>
        </n-form-item>
      </n-form>
    </div>
    <div class="dreamer-toolbar">
      <n-button type="primary" size="small" @click="handleToAddClick">添加</n-button>
    </div>
    <n-data-table :columns="columns" :data="tableData.records" size="small" striped bordered />

    <div class="dreamer-pagination">
      <n-pagination v-model:page="searchForm.current" :page-count="tableData.pages" :on-update:page="handlePageChange" />
    </div>
  </n-space>

  <n-modal :title="modalTitle" v-model:show="showModal" :mask-closable="false" :show-icon="false" preset="dialog" size="small" style="width: 500px">
    <n-form ref="formRef" :label-width="80" :model="formData" :rules="rules" size="small">
      <n-grid x-gap="12" :cols="2">
        <n-gi>
          <n-form-item label="用户名" path="username">
            <n-input v-model:value="formData.username" placeholder="请输入用户名" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="真实姓名" path="realname">
            <n-input v-model:value="formData.realname" placeholder="请输入真实姓名" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="密码" path="password">
            <n-input type="password" v-model:value="formData.password" placeholder="请输入密码" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="重复密码" path="repassword">
            <n-input type="password" v-model:value="formData.repassword" placeholder="请再次输入密码" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="手机号" path="mobile">
            <n-input v-model:value="formData.mobile" placeholder="请输入手机号" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="状态" path="status">
            <n-radio-group v-model:value="formData.status">
              <n-space>
                <n-radio label="启用" value="1" />
                <n-radio label="禁用" value="0" />
              </n-space>
            </n-radio-group>
          </n-form-item>
        </n-gi>
      </n-grid>

      <div class="dreamer-modal-footer">
        <n-space>
          <n-button type="default" size="small" attr-type="button" @click="showModal = false">取消</n-button>
          <n-button type="primary" size="small" attr-type="button" @click="handleSaveClick">保存</n-button>
        </n-space>
      </div>
    </n-form>
  </n-modal>
</template>

<style scoped lang="less">
:deep(.n-form-item-label){
  color: #333333 !important;
}
</style>
